package com.example.myapplication;

import android.os.AsyncTask;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class RemoteDataBaseConnector extends AsyncTask<Void, Void, Connection> {
  //private static final String URL = "jdbc:mysql://lickoo.imdo.co:3306/wcj";
  //private static final String URL = "jdbc:mysql://lickoo.imdo.co:3306/wcj?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true";
  private static final String URL = "jdbc:mysql://lickoo.imdo.co:3306/wcj?useSSL=false";
  private static final String USERNAME = "wcj";
  private static final String USERPASSWORD = "wcj1234";


  public static final String DATABASE_NAME = "wcj.db";
  public static final String USER_TABLE = "users";
  public static final String NOTE_TABLE = "notes";
  public static final String DELETE_TABLE = "deletenotes";

  private RemoteDatabaseCallback callback;
  Connection connection = null;
  public RemoteDataBaseConnector(RemoteDatabaseCallback callback) {
    this.callback = callback;
  }
  public static Connection GetConnection() throws SQLException, ClassNotFoundException {
    //Class.forName("com.mysql.cj.jdbc.Driver");
    ////Class.forName("com.mysql.jdbc.Driver");
    //return DriverManager.getConnection(URL, USERNAME, USERPASSWORD);
    //链接数据库并执行查询语句，获取结果
    //Class.forName("com.mysql.cj.jdbc.Driver");
    //String url="jdbc:mysql://localhost:3306/shopmanager?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
    //String user="root";
    //String password="200326";
    //return DriverManager.getConnection(url,user,password);
    try {
      //Class.forName("com.mysql.cj.jdbc.Driver");
      Class.forName("com.mysql.jdbc.Driver");
      return DriverManager.getConnection(URL, USERNAME, USERPASSWORD);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }

  }
  public Connection ReturnConnection() {
    return connection;
  }

  @Override protected Connection doInBackground(Void... voids) {


    try {
      //Class.forName("com.mysql.cj.jdbc.Driver");
      Class.forName("com.mysql.jdbc.Driver");
      connection = DriverManager.getConnection(URL, USERNAME, USERPASSWORD);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
    return connection;
  }

  @Override protected void onPostExecute(Connection connection) {
    if (connection != null) {
      if (callback != null) {
        System.out.println("连接成功");

        callback.onConnectionObtained(connection);

      }
    } else {
      System.out.println("链接失败");

    }
  }
}
